<template>
  <div class="system-logs-container">
    <div class="header">
      <h2>系统日志</h2>
      <p>查看和管理系统操作日志</p>
    </div>

    <!-- 日志筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="filterForm.operationType" placeholder="请选择操作类型" clearable>
            <el-option label="登录" value="LOGIN" />
            <el-option label="登出" value="LOGOUT" />
            <el-option label="创建" value="CREATE" />
            <el-option label="更新" value="UPDATE" />
            <el-option label="删除" value="DELETE" />
            <el-option label="查询" value="QUERY" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户">
          <el-input v-model="filterForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchLogs">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 日志列表 -->
    <el-card class="logs-card">
      <template #header>
        <div class="card-header">
          <span>操作日志列表</span>
          <div>
            <el-button type="danger" @click="clearAllLogs" :disabled="logs.length === 0">清空所有日志</el-button>
            <el-button @click="exportToExcel">导出日志</el-button>
          </div>
        </div>
      </template>

      <el-table :data="paginatedLogs" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="timestamp" label="操作时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="操作用户" width="120" />
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="scope">
            <el-tag :type="getOperationTypeTag(scope.row.operationType)">
              {{ formatOperationType(scope.row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="操作模块" width="120" />
        <el-table-column prop="description" label="操作描述" show-overflow-tooltip />
        <el-table-column prop="ipAddress" label="IP地址" width="200">
          <template #default="scope">
            <div class="ip-address-cell">
              <el-popover
                placement="top-start"
                title="IP地址详情"
                :width="300"
                trigger="hover"
                v-if="scope.row.ipAddress && scope.row.ipAddress.includes(';')"
              >
                <template #reference>
                  <span class="ip-main">{{ getMainIp(scope.row.ipAddress) }}</span>
                  <el-tag size="small" type="info" style="margin-left: 5px;">有代理</el-tag>
                </template>
                <div class="ip-detail">
                  <div><strong>直接连接IP:</strong> {{ getMainIp(scope.row.ipAddress) }}</div>
                  <div v-for="proxy in getProxyInfo(scope.row.ipAddress)" :key="proxy.header">
                    <strong>{{ proxy.header }}:</strong> {{ proxy.ips }}
                  </div>
                </div>
              </el-popover>
              <span v-else>
                {{ scope.row.ipAddress || 'unknown' }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" @click="viewLogDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalLogs"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="日志详情" width="600px">
      <el-form label-width="100px" v-if="selectedLog">
        <el-form-item label="操作时间">
          <el-input v-model="formattedSelectedLogTime" readonly />
        </el-form-item>
        <el-form-item label="操作用户">
          <el-input v-model="selectedLog.username" readonly />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-input v-model="selectedLog.operationType" readonly />
        </el-form-item>
        <el-form-item label="操作模块">
          <el-input v-model="selectedLog.module" readonly />
        </el-form-item>
        <el-form-item label="操作描述">
          <el-input v-model="selectedLog.description" type="textarea" readonly />
        </el-form-item>
        <el-form-item label="IP地址">
          <div v-if="selectedLog && selectedLog.ipAddress">
            <div><strong>直接连接IP:</strong> {{ getMainIp(selectedLog.ipAddress) }}</div>
            <div v-for="proxy in getProxyInfo(selectedLog.ipAddress)" :key="proxy.header">
              <strong>{{ proxy.header }}:</strong> {{ proxy.ips }}
            </div>
          </div>
          <el-input v-else v-model="selectedLog.ipAddress" readonly />
        </el-form-item>
        <el-form-item label="用户代理">
          <el-input v-model="selectedLog.userAgent" type="textarea" readonly />
        </el-form-item>
        <el-form-item label="请求参数">
          <el-input v-model="selectedLog.requestParams" type="textarea" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElPagination } from 'element-plus'
import request from '../../utils/request'
import { logApi } from '../../utils/logApi'
import * as XLSX from 'xlsx'

// 响应式数据
const logs = ref<any[]>([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const selectedLog = ref<any>(null)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const totalLogs = ref(0)

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  operationType: '',
  username: ''
})

// 计算属性：分页后的日志（现在由后端处理分页）
const paginatedLogs = computed(() => {
  // 由于后端已经处理了分页，这里直接返回日志数据
  // 如果需要前端分页，可以取消下面的注释并使用
  /*
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return logs.value.slice(start, end)
  */
  return logs.value
})

// 格式化后的时间（用于详情对话框）
const formattedSelectedLogTime = computed(() => {
  if (selectedLog.value) {
    return formatDate(selectedLog.value.timestamp)
  }
  return ''
})

// 格式化日期时间
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取操作类型标签样式
const getOperationTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'LOGIN': 'success',
    'LOGOUT': 'info',
    'CREATE': 'primary',
    'UPDATE': 'warning',
    'DELETE': 'danger',
    'QUERY': 'info'
  }
  return tagMap[type] || 'info'
}

// 格式化操作类型显示
const formatOperationType = (type: string) => {
  const typeMap: Record<string, string> = {
    'LOGIN': '登录',
    'LOGOUT': '登出',
    'CREATE': '创建',
    'UPDATE': '更新',
    'DELETE': '删除',
    'QUERY': '查询'
  }
  return typeMap[type] || type
}

// 获取主要IP地址（直接连接的IP）
const getMainIp = (ipAddress: string) => {
  if (!ipAddress) return 'unknown'
  // 如果包含分号，说明有代理信息，取分号前的部分
  if (ipAddress.includes(';')) {
    return ipAddress.split(';')[0]
  }
  return ipAddress
}

// 获取代理信息
const getProxyInfo = (ipAddress: string) => {
  if (!ipAddress || !ipAddress.includes(';')) return []

  const proxyInfo: Array<{header: string, ips: string}> = []
  const parts = ipAddress.split(';')

  // 跳过第一个部分（直接IP），处理后续的代理信息
  for (let i = 1; i < parts.length; i++) {
    const part = parts[i]
    const colonIndex = part.indexOf(':')
    if (colonIndex > 0) {
      const header = part.substring(0, colonIndex)
      const ips = part.substring(colonIndex + 1)
      proxyInfo.push({ header, ips })
    }
  }

  return proxyInfo
}

// 查询日志
const searchLogs = async () => {
  loading.value = true
  try {
    // 构造查询参数
    const params: any = {
      page: currentPage.value - 1, // 后端分页从0开始
      size: pageSize.value
    }

    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.startTime = filterForm.dateRange[0]
      params.endTime = filterForm.dateRange[1]
    }
    if (filterForm.operationType) {
      params.operationType = filterForm.operationType
    }
    if (filterForm.username) {
      params.username = filterForm.username
    }

    // 调用后端API获取日志数据
    const response = await logApi.getLogs(params)
    const data = response.data

    // 处理后端返回的分页数据
    if (data && data.content && Array.isArray(data.content)) {
      // 后端返回的是Page对象
      logs.value = data.content
      totalLogs.value = data.totalElements || 0
    } else if (data && Array.isArray(data)) {
      // 后端返回的是数组
      logs.value = data
      totalLogs.value = data.length
    } else {
      // 其他情况，设置为空数组
      logs.value = []
      totalLogs.value = 0
    }
    
    // 强制触发响应式更新
    await nextTick()
    
    
    ElMessage.success('查询成功')
  } catch (error) {
    console.error('查询日志失败:', error)
    ElMessage.error('查询日志失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 导出日志到Excel
const exportToExcel = () => {
  if (logs.value.length === 0) {
    ElMessage.warning('没有可导出的日志数据')
    return
  }

  // 准备导出数据
  const exportData = logs.value.map(log => ({
    '操作时间': formatDate(log.timestamp),
    '操作用户': log.username,
    '操作类型': formatOperationType(log.operationType),
    '操作模块': log.module,
    '操作描述': log.description,
    'IP地址': log.ipAddress,
    '浏览器信息': log.userAgent,
    '请求参数': log.requestParams
  }))

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(exportData)

  // 设置列宽
  const colWidths = [
    { wch: 20 }, // 操作时间
    { wch: 15 }, // 操作用户
    { wch: 12 }, // 操作类型
    { wch: 15 }, // 操作模块
    { wch: 30 }, // 操作描述
    { wch: 20 }, // IP地址
    { wch: 30 }, // 浏览器信息
    { wch: 50 }  // 请求参数
  ]
  worksheet['!cols'] = colWidths

  // 创建工作簿并添加工作表
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '系统日志')

  // 生成文件名
  const fileName = `系统日志_${formatDateForFilename(new Date())}.xlsx`

  // 导出文件
  XLSX.writeFile(workbook, fileName)

  ElMessage.success('日志导出成功')
}

// 格式化日期用于文件名
const formatDateForFilename = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`
}

// 重置筛选条件
const resetFilters = () => {
  filterForm.dateRange = []
  filterForm.operationType = ''
  filterForm.username = ''
  searchLogs()
}

// 清空所有日志
const clearAllLogs = () => {
  ElMessageBox.confirm(
    '确定要清空所有系统日志吗？此操作不可恢复。',
    '确认清空',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await logApi.deleteAllLogs()
      logs.value = []
      totalLogs.value = 0
      ElMessage.success('日志已清空')
    } catch (error) {
      console.error('清空日志失败:', error)
      ElMessage.error('清空日志失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    // 取消操作
  })
}

// 导出日志
const exportLogs = () => {
  ElMessage.info('导出功能待实现')
}

// 查看日志详情
const viewLogDetail = (log: any) => {
  selectedLog.value = log
  detailDialogVisible.value = true
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  searchLogs()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  searchLogs()
}

// 组件挂载时加载日志
onMounted(() => {
  searchLogs()
})
</script>

<style scoped>
.system-logs-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.header p {
  color: #606266;
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logs-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.ip-address-cell {
  display: flex;
  align-items: center;
}

.ip-main {
  font-family: monospace;
}

.ip-detail {
  font-family: monospace;
  font-size: 12px;
}

.ip-detail div {
  margin-bottom: 5px;
}
</style>
